//
//  BDPostCommentLayout.m
//  BadBoy
//
//  Created by wen on 2017/9/6.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDPostCommentLayout.h"
#import "BDPostHelper.h"
#import "BDTextLinePositionModifier.h"

@implementation BDPostCommentLayout

- (instancetype)initWithComment:(BDPostCommentModel *)comment {
    if (!comment || !comment.user) return nil;
    if (self = [super init]) {
        _comment = comment;
        [self layout];
    }
    return self;
}

- (void)layout{
    [self _layout];
    [self _calculateHeight];
}

- (void)_layout {
    _profileHeight = 0;
    _commentHeight = 0;
    
    _marginBottom = kBDCommentBottomMargin;
    
    [self _layoutProfile];
    [self _layoutComment];
    [self _layoutReply];
}

- (void)_calculateHeight {
    _height = 0;
    _height += _profileHeight;
    
    if (_replyHeight.count) {
        _commentHeight += kBDCommentPaddingText;
    }
    
    _height += _commentHeight;
    
    //回复部分
    _replyTableViewHeight = 0;
    for (NSNumber *cellHeight in _replyHeight) {
        _replyTableViewHeight += cellHeight.floatValue;
    }
    _height += _replyTableViewHeight;
    _height += _marginBottom;
}

///用户信息
- (void)_layoutProfile {
    [self _layoutName];
    [self _layoutSource];
    _profileHeight = kBDCommentProfileHeight;
}

- (void)_layoutName {
    BDUserModel *user = _comment.user;
    NSString *nameStr = user.nickname;
    if (nameStr.length == 0) {
        _nameTextLayout = nil;
        return;
    }
    
    NSMutableAttributedString *nameText = [[NSMutableAttributedString alloc] initWithString:nameStr];
    
    // VIP
    if (user.vip_level > 0) {
        UIImage *yelllowVImage = [BDPostHelper imageNamed:@"user_vip"];
        NSAttributedString *vipText = [BDPostHelper attachmentWithFontSize:kBDCommentNameFontSize image:yelllowVImage shrink:NO];
        [nameText appendString:@" "];
        [nameText appendAttributedString:vipText];
    }
    
    nameText.font = [UIFont systemFontOfSize:kBDCommentNameFontSize];
    nameText.color = user.vip_level > 0 ? kBDCommentNameOrangeColor : kBDCommentNameNormalColor;
    nameText.lineBreakMode = NSLineBreakByCharWrapping;
    
    YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(kBDCommentNameWidth, 9999)];
    container.maximumNumberOfRows = 1;
    _nameTextLayout = [YYTextLayout layoutWithContainer:container text:nameText];
}

- (void)_layoutSource {
    NSMutableAttributedString *sourceText = [NSMutableAttributedString new];
    NSString *createTime = [BDPostHelper stringWithTimelineDate:[NSDate dateWithTimeIntervalSince1970:_comment.commented_at.integerValue]];
    
    // 时间
    if (createTime.length) {
        NSMutableAttributedString *timeText = [[NSMutableAttributedString alloc] initWithString:createTime];
        [timeText appendString:@"  "];
        timeText.font = [UIFont systemFontOfSize:kBDCommentSourceFontSize];
        timeText.color = kBDCommentTimeNormalColor;
        [sourceText appendAttributedString:timeText];
    }
    
    if (sourceText.length == 0) {
        _sourceTextLayout = nil;
    } else {
        YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(kBDCommentNameWidth, 9999)];
        container.maximumNumberOfRows = 1;
        _sourceTextLayout = [YYTextLayout layoutWithContainer:container text:sourceText];
    }
}

- (void)_layoutComment {
    _commentHeight = 0;
    _commentLayout = nil;
    
    NSMutableAttributedString *text = [self _textWithComment:_comment
                                                     isReply:NO
                                                    fontSize:kBDCommentTextFontSize
                                                   textColor:kBDCommentTextNormalColor];
    if (text.length == 0) return;
    
    BDTextLinePositionModifier *modifier = [BDTextLinePositionModifier new];
    modifier.font = [UIFont fontWithName:@"Heiti SC" size:kBDCommentTextFontSize];
    modifier.paddingTop = kBDCommentPaddingText;
    modifier.paddingBottom = kBDCommentPaddingText;
    
    YYTextContainer *container = [YYTextContainer new];
    container.size = CGSizeMake(kBDCommentContentWidth, MAXFLOAT);
    container.linePositionModifier = modifier;
    
    _commentLayout = [YYTextLayout layoutWithContainer:container text:text];
    if (!_commentLayout) return;
    
    _commentHeight = [modifier heightForLineCount:_commentLayout.rowCount];
}

- (void)_layoutReply {
    _replyHeight = [NSMutableArray array];
    _replyLayout = [NSMutableArray array];
    
    for (BDPostCommentModel *replyModel in _comment.sub_comments) {
        NSMutableAttributedString *text = [self _textWithComment:replyModel
                                                         isReply:YES
                                                        fontSize:kBDCommentTextFontReplySize
                                                       textColor:kBDCommentTextNormalColor];
        if (text.length == 0) return;
        
        BDTextLinePositionModifier *modifier = [BDTextLinePositionModifier new];
        modifier.font = [UIFont fontWithName:@"Heiti SC" size:kBDCommentTextFontReplySize];
        modifier.paddingTop = kBDCommentPaddingText;
        modifier.paddingBottom = kBDCommentPaddingText;
        
        YYTextContainer *container = [YYTextContainer new];
        container.size = CGSizeMake(kBDCommentContentWidth - 10, HUGE);
        container.linePositionModifier = modifier;
        
        YYTextLayout *replyLayout = [YYTextLayout layoutWithContainer:container text:text];
        if (!_replyLayout) return;
        [_replyLayout addObject:replyLayout];
        [_replyHeight addObject:@([modifier heightForLineCount:replyLayout.lines.count])];
    }
}

///对文本的处理
- (NSMutableAttributedString *)_textWithComment:(BDPostCommentModel *)comment
                                        isReply:(BOOL)isReply
                                       fontSize:(CGFloat)fontSize
                                      textColor:(UIColor *)textColor {
    if (!comment) return nil;
    
    // 字体
    UIFont *font = [UIFont systemFontOfSize:fontSize];
    
    NSMutableAttributedString *text = [NSMutableAttributedString new];
    
    if (isReply == NO) {
        [text appendAttributedString:[[NSMutableAttributedString alloc] initWithString:comment.comment]];
        text.font = font;
        text.color = textColor;
    }else{
        NSString *labelStr = nil;
        if (comment.reply_user) {
            labelStr = [NSString stringWithFormat:ASLocalizedString(@"%@：回复%@ %@"), comment.user.nickname, comment.reply_user.nickname, comment.comment];
        }else{
            labelStr = [NSString stringWithFormat:@"%@：%@", comment.user.nickname, comment.comment];
        }
        NSMutableAttributedString *reply = [[NSMutableAttributedString alloc] initWithString:labelStr];
        NSRange range = [labelStr rangeOfString:comment.user.nickname];
        reply.font = font;
        reply.color = textColor;
        [reply setColor:KBDColorBlue range:range];
        [text appendAttributedString:reply];
    }
    
    // 高亮状态的背景
    YYTextBorder *highlightBorder = [YYTextBorder new];
    highlightBorder.insets = UIEdgeInsetsMake(-2, 0, -2, 0);
    highlightBorder.cornerRadius = 3;
    highlightBorder.fillColor = kBDCommentTextHighlightBackgroundColor;
    
    
    
    //    // 根据 urlStruct 中每个 URL.shortURL 来匹配文本，将其替换为图标+友好描述
    //    for (WBURL *wburl in status.urlStruct) {
    //        if (wburl.shortURL.length == 0) continue;
    //        if (wburl.urlTitle.length == 0) continue;
    //        NSString *urlTitle = wburl.urlTitle;
    //        if (urlTitle.length > 27) {
    //            urlTitle = [[urlTitle substringToIndex:27] stringByAppendingString:YYTextTruncationToken];
    //        }
    //        NSRange searchRange = NSMakeRange(0, text.string.length);
    //        do {
    //            NSRange range = [text.string rangeOfString:wburl.shortURL options:kNilOptions range:searchRange];
    //            if (range.location == NSNotFound) break;
    //
    //            if (range.location + range.length == text.length) {
    //                if (status.pageInfo.pageID && wburl.pageID &&
    //                    [wburl.pageID isEqualToString:status.pageInfo.pageID]) {
    //                    if ((!isRetweet && !status.retweetedStatus) || isRetweet) {
    //                        if (status.pics.count == 0) {
    //                            [text replaceCharactersInRange:range withString:@""];
    //                            break; // cut the tail, show with card
    //                        }
    //                    }
    //                }
    //            }
    //
    //            if ([text attribute:YYTextHighlightAttributeName atIndex:range.location] == nil) {
    //
    //                // 替换的内容
    //                NSMutableAttributedString *replace = [[NSMutableAttributedString alloc] initWithString:urlTitle];
    //                if (wburl.urlTypePic.length) {
    //                    // 链接头部有个图片附件 (要从网络获取)
    //                    NSURL *picURL = [WBStatusHelper defaultURLForImageURL:wburl.urlTypePic];
    //                    UIImage *image = [[YYImageCache sharedCache] getImageForKey:picURL.absoluteString];
    //                    NSAttributedString *pic = (image && !wburl.pics.count) ? [self _attachmentWithFontSize:fontSize image:image shrink:YES] : [self _attachmentWithFontSize:fontSize imageURL:wburl.urlTypePic shrink:YES];
    //                    [replace insertAttributedString:pic atIndex:0];
    //                }
    //                replace.font = font;
    //                replace.color = kWBCellTextHighlightColor;
    //
    //                // 高亮状态
    //                YYTextHighlight *highlight = [YYTextHighlight new];
    //                [highlight setBackgroundBorder:highlightBorder];
    //                // 数据信息，用于稍后用户点击
    //                highlight.userInfo = @{kWBLinkURLName : wburl};
    //                [replace setTextHighlight:highlight range:NSMakeRange(0, replace.length)];
    //
    //                // 添加被替换的原始字符串，用于复制
    //                YYTextBackedString *backed = [YYTextBackedString stringWithString:[text.string substringWithRange:range]];
    //                [replace setTextBackedString:backed range:NSMakeRange(0, replace.length)];
    //
    //                // 替换
    //                [text replaceCharactersInRange:range withAttributedString:replace];
    //
    //                searchRange.location = searchRange.location + (replace.length ? replace.length : 1);
    //                if (searchRange.location + 1 >= text.length) break;
    //                searchRange.length = text.length - searchRange.location;
    //            } else {
    //                searchRange.location = searchRange.location + (searchRange.length ? searchRange.length : 1);
    //                if (searchRange.location + 1>= text.length) break;
    //                searchRange.length = text.length - searchRange.location;
    //            }
    //        } while (1);
    //    }
    //
    //    // 根据 topicStruct 中每个 Topic.topicTitle 来匹配文本，标记为话题
    //    for (WBTopic *topic in status.topicStruct) {
    //        if (topic.topicTitle.length == 0) continue;
    //        NSString *topicTitle = [NSString stringWithFormat:@"#%@#",topic.topicTitle];
    //        NSRange searchRange = NSMakeRange(0, text.string.length);
    //        do {
    //            NSRange range = [text.string rangeOfString:topicTitle options:kNilOptions range:searchRange];
    //            if (range.location == NSNotFound) break;
    //
    //            if ([text attribute:YYTextHighlightAttributeName atIndex:range.location] == nil) {
    //                [text setColor:kWBCellTextHighlightColor range:range];
    //
    //                // 高亮状态
    //                YYTextHighlight *highlight = [YYTextHighlight new];
    //                [highlight setBackgroundBorder:highlightBorder];
    //                // 数据信息，用于稍后用户点击
    //                highlight.userInfo = @{kWBLinkTopicName : topic};
    //                [text setTextHighlight:highlight range:range];
    //            }
    //            searchRange.location = searchRange.location + (searchRange.length ? searchRange.length : 1);
    //            if (searchRange.location + 1>= text.length) break;
    //            searchRange.length = text.length - searchRange.location;
    //        } while (1);
    //    }
    
    // 匹配 @用户名
    NSArray *atResults = [[BDPostHelper regexAt] matchesInString:text.string options:kNilOptions range:text.rangeOfAll];
    for (NSTextCheckingResult *at in atResults) {
        if (at.range.location == NSNotFound && at.range.length <= 1) continue;
        if ([text attribute:YYTextHighlightAttributeName atIndex:at.range.location] == nil) {
            [text setColor:kBDCommentTextHighlightColor range:at.range];
            
            // 高亮状态
            YYTextHighlight *highlight = [YYTextHighlight new];
            [highlight setBackgroundBorder:highlightBorder];
            // 数据信息，用于稍后用户点击
            highlight.userInfo = @{kBDLinkAtName : [text.string substringWithRange:NSMakeRange(at.range.location + 1, at.range.length - 1)]};
            [text setTextHighlight:highlight range:at.range];
        }
    }
    
    // 匹配 [表情]
    NSArray<NSTextCheckingResult *> *emoticonResults = [[BDPostHelper regexEmoticon] matchesInString:text.string options:kNilOptions range:text.rangeOfAll];
    NSUInteger emoClipLength = 0;
    for (NSTextCheckingResult *emo in emoticonResults) {
        if (emo.range.location == NSNotFound && emo.range.length <= 1) continue;
        NSRange range = emo.range;
        range.location -= emoClipLength;
        if ([text attribute:YYTextHighlightAttributeName atIndex:range.location]) continue;
        if ([text attribute:YYTextAttachmentAttributeName atIndex:range.location]) continue;
        NSString *emoString = [text.string substringWithRange:range];
        NSString *imageName = [BDPostHelper emoticonDic][emoString][@"gif"];
        
        UIImage *image = [BDPostHelper imageNamed:imageName];
        if (!image) continue;
        
        NSAttributedString *emoText = [NSAttributedString attachmentStringWithEmojiImage:image fontSize:fontSize];
        [text replaceCharactersInRange:range withAttributedString:emoText];
        emoClipLength += range.length - 1;
    }
    return text;
}

@end
